package com.xiaoqianxin.pang_rowth.pang_rowth_plugin

import android.util.Log
import com.bytedance.sdk.djx.DJXSdk
import com.bytedance.sdk.djx.DJXSdkConfig
import com.bytedance.sdk.djx.interfaces.listener.IDJXAdListener
import com.bytedance.sdk.djx.interfaces.listener.IDJXDramaHomeListener
import com.bytedance.sdk.djx.interfaces.listener.IDJXDramaListener
import com.bytedance.sdk.djx.interfaces.listener.IDJXDramaUnlockListener
import com.bytedance.sdk.djx.model.DJXDrama
import com.bytedance.sdk.djx.model.DJXDramaDetailConfig
import com.bytedance.sdk.djx.model.DJXDramaUnlockAdMode
import com.bytedance.sdk.djx.model.DJXError
import com.bytedance.sdk.djx.params.DJXWidgetDramaHomeParams
import com.xiaoqianxin.pang_rowth.pang_rowth_plugin.utils.DefaultAdListener
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** PangRowthPlugin */
class PangRowthPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private var application: android.app.Application? = null
    private var activity: android.app.Activity? = null
    val FREE_SET = 5
    val LOCK_SET = 2
    private val TAG = "PangRowthPlugin"

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "pang_rowth_plugin")
        channel.setMethodCallHandler(this)
        application = flutterPluginBinding.applicationContext as android.app.Application
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "init" -> {
                init(call, result)
            }

            "loadDJX" -> {
                loadDJX(call, result)
            }

            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    // ActivityAware接口实现
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivity() {
        activity = null
    }

    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    private fun loadDJX(call: MethodCall, result: Result) {
        try {
            activity?.let { currentActivity ->
                // 启动新的Activity来展示短剧
                DramaActivity.start(currentActivity)
                result.success(true)
            } ?: run {
                Log.w(TAG, "Activity为空，无法启动短剧页面")
                result.success(false)
            }
        } catch (e: SecurityException) {
            Log.e(TAG, "权限不足，启动短剧Activity失败", e)
            result.success(false)
        } catch (e: IllegalStateException) {
            Log.e(TAG, "状态异常，启动短剧Activity失败", e)
            result.success(false)
        } catch (e: Exception) {
            Log.e(TAG, "启动短剧Activity失败", e)
            result.success(false)
        }
    }

    private fun init(call: MethodCall, result: Result) {
        try {
            val mDJXJson = call.argument<String>("DJXJson")

            // 参数验证
            if (mDJXJson.isNullOrEmpty()) {
                Log.w(TAG, "DJXJson参数为空")
                result.success(false)
                return
            }

            if (application == null) {
                Log.w(TAG, "Application为空，无法初始化SDK")
                result.success(false)
                return
            }

            // 初始化SDK
            val config = DJXSdkConfig.Builder().build()
            DJXSdk.init(application!!, mDJXJson, config)
            DJXSdk.start { isSuccess, message, error ->
                try {
                    if (isSuccess) {
                        Log.i(TAG, "DJX SDK初始化成功")
                        result.success(true)
                    } else {
                        Log.e(TAG, "DJX SDK启动失败: $message, error: $error")
                        result.error("SDK_START_FAILED", "SDK启动失败: $message", error?.toString())
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "SDK启动回调处理异常", e)
                    result.error("CALLBACK_ERROR", "SDK启动回调处理异常：${e.message}", e.toString())
                }
            }

        } catch (e: IllegalArgumentException) {
            Log.e(TAG, "参数错误，初始化SDK失败", e)
            result.success(false)
        } catch (e: SecurityException) {
            Log.e(TAG, "权限不足，初始化SDK失败", e)
            result.success(false)
        } catch (e: IllegalStateException) {
            Log.e(TAG, "状态异常，初始化SDK失败", e)
            result.success(false)
        } catch (e: Exception) {
            Log.e(TAG, "初始化SDK失败", e)
            result.success(false)
        }
    }

}